package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Maps;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.service.ArticleInfoService;
import com.heima.common.exception.LeadNewsException;
import com.heima.model.article.dto.ArticleInfoDto;
import com.heima.model.article.pojo.ApArticleConfig;
import com.heima.model.article.pojo.ApArticleContent;
import com.heima.model.common.dto.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.sun.javaws.ui.LaunchErrorDialog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.Objects;

/**
 * @author Ronaldo
 * @date 2021/8/13
 */
@Service
@Transactional
@Slf4j
public class ArticleInfoServiceImpl implements ArticleInfoService {

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Override
    public ResponseResult getArticleInfoById(ArticleInfoDto articleInfoDto) {

        if (Objects.isNull(articleInfoDto.getArticleId())){
            throw new LeadNewsException(AppHttpCodeEnum.PARAM_INVALID);
        }

        //查询文章配置信息是否存在
        ApArticleConfig articleConfig = apArticleConfigMapper.selectOne(Wrappers.<ApArticleConfig>lambdaQuery()
                .eq(ApArticleConfig::getArticleId, articleInfoDto.getArticleId()));
        if (Objects.isNull(articleConfig)){
            throw new LeadNewsException(AppHttpCodeEnum.NOT_FOUND_ARTICLE_CONFIG);
        }

        //判断文章是否已下架 或 已删除
        if (articleConfig.getIsDelete()){
            throw new LeadNewsException(AppHttpCodeEnum.ARTICLE_IS_DELETE);
        }
        if (articleConfig.getIsDown()){
            throw new LeadNewsException(AppHttpCodeEnum.ARTICLE_IS_DOWN);
        }

        //查询文章内容信息
        ApArticleContent articleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery()
                .eq(ApArticleContent::getArticleId, articleInfoDto.getArticleId()));
        if (Objects.isNull(articleContent)){
            throw new LeadNewsException(AppHttpCodeEnum.NOT_FOUND_ARTICLE_CONTENT);
        }

        Map<String,Object> resultMap = Maps.newHashMap();
        resultMap.put("config",articleConfig);
        resultMap.put("content",articleContent);

        return ResponseResult.okResult(resultMap);
    }
}
